package cn.icatw.wallpaperapi.service.impl;

import cn.icatw.wallpaperapi.domain.Collect;
import cn.icatw.wallpaperapi.domain.Image;
import cn.icatw.wallpaperapi.domain.dto.ImageDto;
import cn.icatw.wallpaperapi.domain.vo.ImageVo;
import cn.icatw.wallpaperapi.mapper.CollectMapper;
import cn.icatw.wallpaperapi.mapper.ImageMapper;
import cn.icatw.wallpaperapi.service.ImageService;
import cn.icatw.wallpaperapi.utils.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 壁纸表(Image)表服务实现类
 *
 * @author icatw
 * @since 2022-10-14 19:58:55
 */
@Service("imageService")
@Slf4j
public class ImageServiceImpl extends ServiceImpl<ImageMapper, Image> implements ImageService {
    @Resource
    JwtUtil jwtUtil;
    @Resource
    CollectMapper collectMapper;

    @Override
    public Page<ImageVo> pageList(String name, int current, int size, HttpServletRequest request, ImageDto imageDto) {
        String userId = jwtUtil.getClaimByToken(request);
        //判断用户是否登录，如果未登陆收藏状态status为0
        //如果已登陆，查询图片是否收藏
        Page<ImageVo> page = new Page<>(current, size);
        Page<ImageVo> resultVo = baseMapper.queryPageVoList(page, imageDto);
        //如果登陆用户，查询用户收藏信息
        if (userId != null) {
            resultVo.getRecords().forEach(vo -> {
                //遍历查询图片是否被收藏
                Long imageId = vo.getId();
                //查询该图片是否被该用户收藏
                Collect collect = collectMapper.selectOne(new LambdaQueryWrapper<Collect>()
                        .eq(Collect::getUserId, userId)
                        .eq(Collect::getImageId, imageId)
                        .eq(Collect::getStatus, 1));
                if (collect != null) {
                    //    非空，表示为收藏状态
                    vo.setStatus(1);
                }
            });
        }
        return resultVo;

    }

    @Override
    public Page<ImageVo> getByName(String name, int current, int size, HttpServletRequest request) {
        String userId = jwtUtil.getClaimByToken(request);
        //判断用户是否登录，如果未登陆收藏状态status为0
        //如果已登陆，查询图片是否收藏
        Page<ImageVo> page = new Page<>(current, size);
        return baseMapper.queryPageVoListByName(page, name,userId);
        //Page<Image> page = new Page<>(current, size);
        //LambdaQueryWrapper<Image> wrapper = new LambdaQueryWrapper<>();
        //if (name != null) {
        //    wrapper.like(Image::getImageName, name);
        //}
        //Page<Image> imagePage = page(page, wrapper);
        //List<ImageVo> imageVos = BeanCopyUtil.copyBeanList(imagePage.getRecords(), ImageVo.class);
        //

    }
}

